import Access from '@/components/Access';
import HandleBtn from '@/components/HandleBar/btn';
import type { ActionType, ProColumns, ProFormInstance } from '@/components/Pro/';
import { ModalForm, ProFormText, ProFormTextArea, ProTable } from '@/components/Pro/';
import {
  sysDictTypeControllerDeleteBatch as batchDelete,
  sysDictTypeControllerEdit as edit,
  sysDictTypeControllerExport as downloadFile,
  sysDictTypeControllerGenerateTypeCode as generateTypeCode,
  sysDictTypeControllerPageList as getList,
  sysDictTypeControllerSave as add,
  sysDictTypeControllerSaveBatch as uploadFile,
} from '@/services/ess/sysDict';
import { downloadFetch } from '@/utils/downloadFile';
import type { UploadProps } from 'antd';
import { message, Modal, Space, Upload } from 'antd';
import React, { useRef, useState } from 'react';
import { getIntl, Link, useIntl } from 'umi';

const { confirm } = Modal;

/**
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.SysDictType) => {
  try {
    const res = await add({
      ...fields,
    });
    if (res.success) {
      message.success(getIntl().formatMessage({ id: 'global.addSuccessfully!' }));
    }
    return true;
  } catch (error) {
    message.error(getIntl().formatMessage({ id: 'global.addFailedTips!' }));
    return false;
  }
};

/**
 * @zh-CN 编辑节点
 * @param fields
 */
const handleEdit = async (fields: API.SysDictType) => {
  try {
    const res = await edit({
      ...fields,
    });
    if (res.success) {
      message.success(getIntl().formatMessage({ id: 'global.editedDuccessfully!' }));
      return true;
    }
    return false;
  } catch (error) {
    message.error(getIntl().formatMessage({ id: 'global.editFailedTips' }));
    return false;
  }
};

/**
 * @zh-CN 删除节点
 * @param selectedRows
 */
const handleRemove = async (selectedRows: API.SysDictType[]) => {
  if (!selectedRows) return true;
  try {
    const ids = selectedRows.map((row) => row.typeId);
    const res = await batchDelete(ids);
    if (res.success) {
      message.success(getIntl().formatMessage({ id: 'global.delSuccess' }));
      return true;
    }
    return false;
  } catch (error) {
    message.error(getIntl().formatMessage({ id: 'global.delFailedTips' }));
    return false;
  }
};

const TableList: React.FC = () => {
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const [currentRow, setCurrentRow] = useState<API.SysDictType>({});
  const [selectedRowsState, setSelectedRows] = useState<API.SysDictType[]>([]);
  const [disabled, setDisabled] = useState(false);
  const intl = useIntl();

  const deleteRow = (rows: API.SysDictType[] = selectedRowsState) => {
    if (rows?.length < 1) {
      message.warning(intl.formatMessage({ id: 'global.leastOne' }));
      return;
    }

    if (disabled) return;
    setDisabled(true);

    confirm({
      title: intl.formatMessage({ id: 'systemManagement.supplementary.prompt' }),
      content: intl.formatMessage({ id: 'global.delTip' }),
      onOk: async () => {
        const res = await handleRemove(rows);
        if (res) {
          setSelectedRows([]);
          actionRef.current?.reloadAndRest?.();
        }
      },
      afterClose: () => {
        setDisabled(false);
      },
    });
  };

  const columns: ProColumns<API.SysDictType>[] = [
    {
      title: intl.formatMessage({ id: 'systemManagement.generalProcedure.SN' }),
      dataIndex: 'pageIndex',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.dataDictionary.dictionaryName' }),
      dataIndex: 'typeName',
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.dataDictionary.dictionaryCode' }),
      dataIndex: 'typeCode',
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.dataDictionary.creationtime' }),
      dataIndex: 'createTime',
      fieldProps: () => {
        return {
          placeholder: intl.formatMessage({ id: 'systemManagement.requiredFields.siteNameOrCode' }),
        };
      },
      hideInSearch: true,
      width: 160,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.dataDictionary.updateTime' }),
      dataIndex: 'modifyTime',
      hideInSearch: true,
      width: 160,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.generalProcedure.operation' }),
      dataIndex: 'option',
      valueType: 'option',
      width: 160,
      render: (_, record) => (
        <Space>
          <Access perm="sys:dict:config" key="config">
            <Link
              to={`/system/dictionary/config?id=${record.typeId}&typeName=${encodeURIComponent(
                record.typeName,
              )}&typeCode=${record.typeCode}&createTime=${record.createTime}&modifyTime=${
                record.modifyTime
              }&remark=${encodeURIComponent(record.remark || '')}`}
              key="param"
            >
              {intl.formatMessage({ id: 'systemManagement.generalProcedure.configuration' })}
            </Link>
          </Access>
          <Access perm="sys:dict:edit" key="edit">
            <a
              key="edit"
              onClick={() => {
                handleModalOpen(true);
                setCurrentRow(record);
              }}
            >
              {intl.formatMessage({ id: 'systemManagement.generalProcedure.edit' })}
            </a>
          </Access>
          <Access perm="sys:dict:del" key="delete">
            <a key="delete" className="global-del-color" onClick={() => deleteRow([record])}>
              {intl.formatMessage({ id: 'systemManagement.generalProcedure.delete' })}
            </a>
          </Access>
        </Space>
      ),
    },
  ];

  const uploadProps: UploadProps = {
    name: 'file',
    multiple: true,
    showUploadList: false,
    customRequest: async (info) => {
      const form = new FormData();
      form.append('file', info.file);
      const res = await uploadFile(form, { ingoreErrorMsg: true });
      if (res?.success) {
        message.success(`${info.file.name} ${intl.formatMessage({ id: 'global.iFileS' })}`);
        actionRef?.current?.reloadAndRest?.();
        return;
      }
      const msg = res?.message;
      message.error(
        `${info.file.name} ${intl.formatMessage({ id: 'global.iFileF' })} ${msg ? ',' + msg : ''}`,
      );
    },
  };

  return (
    <div>
      <ProTable<API.SysDictType, API.PageParams>
        headerTitle={intl.formatMessage({ id: 'systemManagement.dataDictionary.dataDictionary' })}
        actionRef={actionRef}
        formRef={formRef}
        rowKey="typeId"
        toolBarRender={() => [
          <Access perm="sys:dict:add" key="add">
            <HandleBtn
              handleType="add"
              key="add"
              onClick={() => {
                setCurrentRow({});
                handleModalOpen(true);
              }}
            >
              {intl.formatMessage({ id: 'systemManagement.generalProcedure.new' })}
            </HandleBtn>
          </Access>,
          <Access perm="sys:dict:import" key="import">
            <Upload {...uploadProps} key="import">
              <HandleBtn handleType="import">
                {intl.formatMessage({ id: 'systemManagement.generalProcedure.import' })}
              </HandleBtn>
            </Upload>
          </Access>,
          <Access perm="sys:dict:export" key="export">
            <HandleBtn
              handleType="export"
              key="export"
              onClick={() =>
                downloadFetch(downloadFile, {
                  ...formRef?.current?.getFieldsFormatValue(),
                  isEmpty: false,
                })
              }
            >
              {intl.formatMessage({ id: 'systemManagement.generalProcedure.export' })}
            </HandleBtn>
          </Access>,
          <Access perm="sys:dict:del" key="delete">
            <HandleBtn onClick={() => deleteRow()} handleType="delete" key="delete">
              {intl.formatMessage({ id: 'systemManagement.generalProcedure.batchDelete' })}
            </HandleBtn>
          </Access>,
        ]}
        request={getList}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      <ModalForm
        modalProps={{
          destroyOnClose: true,
        }}
        initialValues={{ ...currentRow }}
        title={
          currentRow?.typeId
            ? intl.formatMessage({ id: 'systemManagement.dataDictionary.editDataDictionary' })
            : intl.formatMessage({ id: 'systemManagement.dataDictionary.addDataDictionary' })
        }
        width="660px"
        style={{
          marginRight: 50,
        }}
        colProps={{ md: 12 }}
        request={
          !currentRow?.typeId &&
          (async () => {
            const res = await generateTypeCode();
            return { typeCode: res?.data };
          })
        }
        open={createModalOpen}
        onOpenChange={handleModalOpen}
        onFinish={async (value) => {
          let success;
          if (currentRow?.typeId) {
            success = await handleEdit({ ...currentRow, ...value } as API.SysDictType);
          } else {
            success = await handleAdd(value as API.SysDictType);
          }
          if (success) {
            handleModalOpen(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormText
          name="typeName"
          label={intl.formatMessage({ id: 'systemManagement.dataDictionary.dictionaryName' })}
          rules={[
            {
              required: true,
              message: intl.formatMessage({ id: 'systemManagement.requiredFields.dictionaryName' }),
            },
          ]}
          fieldProps={{
            maxLength: 20,
          }}
        />
        <ProFormText
          name="typeCode"
          label={intl.formatMessage({ id: 'systemManagement.dataDictionary.dictionaryCode' })}
          rules={[
            {
              required: true,
              message: intl.formatMessage({ id: 'systemManagement.requiredFields.dictionaryCode' }),
            },
          ]}
          fieldProps={{
            maxLength: 10,
          }}
        />
        <ProFormTextArea
          colProps={{ md: 24 }}
          label={intl.formatMessage({ id: 'systemManagement.dataDictionary.remarksDescription' })}
          name="remark"
        />
      </ModalForm>
    </div>
  );
};
export default TableList;
